package com.tomorrow.payments_hodgepodge.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.tomorrow.payments_hodgepodge.service.AuthorizeService;
import com.tomorrow.payments_hodgepodge.util.CommonResult;
import lombok.extern.slf4j.Slf4j;
import net.authorize.Environment;
import net.authorize.api.contract.v1.*;
import net.authorize.api.controller.CreateTransactionController;
import net.authorize.api.controller.GetTransactionDetailsController;
import net.authorize.api.controller.base.ApiOperationBase;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * @author Tomorrow
 * @date 2020/11/9 17:02
 */
@Service
@Slf4j
public class AuthorizeServiceImpl implements AuthorizeService {
    @Value("${project.AUTHORIZE.NAME}")
    public String name;
    @Value("${project.AUTHORIZE.TRANSACTION_KEY}")
    public String transactionKey;
    @Value("${project.AUTHORIZE.CURRENCY}")
    public String currency;

    public CommonResult authorizePay(String orderNo) {
        // 设置环境沙盒或生产
        if (true) {
            ApiOperationBase.setEnvironment(Environment.SANDBOX);
        } else {
            ApiOperationBase.setEnvironment(Environment.PRODUCTION);
        }
        // 创建带有商家身份验证详细信息的对象
        MerchantAuthenticationType merchantAuthenticationType = new MerchantAuthenticationType();
        merchantAuthenticationType.setName(name);
        merchantAuthenticationType.setTransactionKey(transactionKey);

        // 填充付款数据
        PaymentType paymentType = new PaymentType();
        CreditCardType creditCard = new CreditCardType();
        creditCard.setCardNumber("5424000000000015");
        creditCard.setExpirationDate("2020-12");
        creditCard.setCardCode("999");
        paymentType.setCreditCard(creditCard);

        // 设置电子邮件地址（可选）
        CustomerDataType customer = new CustomerDataType();
        customer.setEmail("646236438@qq.com");

        // 创建付款交易对象
        TransactionRequestType txnRequest = new TransactionRequestType();
        // 信用卡充值
        txnRequest.setTransactionType(TransactionTypeEnum.AUTH_CAPTURE_TRANSACTION.value());
        txnRequest.setPayment(paymentType);
        txnRequest.setCustomer(customer);
        txnRequest.setCurrencyCode(currency);
        // 商家分配的采购订单号. 字符串，最多25个字符。
        txnRequest.setPoNumber(orderNo);
        txnRequest.setAmount(new BigDecimal(200).setScale(2, RoundingMode.CEILING));

        //创建API请求并为此特定请求设置参数
        CreateTransactionRequest apiRequest = new CreateTransactionRequest();
        apiRequest.setMerchantAuthentication(merchantAuthenticationType);
        apiRequest.setTransactionRequest(txnRequest);
        // 商家为请求分配的参考ID. 字符串，最多20个字符。
        apiRequest.setRefId(orderNo);

        // 呼叫控制器
        CreateTransactionController controller = new CreateTransactionController(apiRequest);
        controller.execute();

        // 得到回应
        CreateTransactionResponse response = controller.getApiResponse();

        log.info("authorize 支付操作返回结果: " + JSONObject.toJSONString(response));

        // 解析响应以确定结果
        if (response != null) {
            // 如果API响应正常，请继续检查事务响应
            if (response.getMessages().getResultCode() == MessageTypeEnum.OK) {
                TransactionResponse result = response.getTransactionResponse();
                if (result.getMessages() != null) {
                    return CommonResult.success("SUCCESS", result.getTransId());
                } else {
                    if (response.getTransactionResponse().getErrors() != null) {
                        return CommonResult.failMessage(500, "Authorize 支付失败", result.getErrors().getError().get(0).getErrorText());
                    }
                }
            } else {
                if (response.getTransactionResponse() != null && response.getTransactionResponse().getErrors() != null) {
                    return CommonResult.failMessage(500, "Authorize 支付异常", response.getTransactionResponse().getErrors().getError().get(0).getErrorText());
                } else {
                    return CommonResult.failMessage(500, "Authorize 支付异常", response.getMessages().getMessage().get(0).getText());
                }
            }
        } else {
            // 响应为空时显示错误代码和消息
            ANetApiResponse errorResponse = controller.getErrorResponse();
            if (!errorResponse.getMessages().getMessage().isEmpty()) {
                return CommonResult.failMessage(500, "Authorize 支付异常", errorResponse.getMessages().getMessage().get(0).getText());
            }
        }
        return CommonResult.fail(500, "NetworkTimeout");
    }

    public CommonResult authorizeRefund(String amount, String transId) {
        // 设置环境沙盒或生产
        if (true) {
            ApiOperationBase.setEnvironment(Environment.SANDBOX);
        } else {
            ApiOperationBase.setEnvironment(Environment.PRODUCTION);
        }
        // 创建带有商家身份验证详细信息的对象
        MerchantAuthenticationType merchantAuthenticationType = new MerchantAuthenticationType();
        merchantAuthenticationType.setName(name);
        merchantAuthenticationType.setTransactionKey(transactionKey);

        // 填充退款数据
        PaymentType paymentType = new PaymentType();
        CreditCardType creditCard = new CreditCardType();
        String bankCard = "5424000000000015";
        creditCard.setCardNumber(bankCard.substring(bankCard.length() - 4));
        creditCard.setExpirationDate("XXXX");
        paymentType.setCreditCard(creditCard);

        // 创建付款交易对象
        TransactionRequestType txnRequest = new TransactionRequestType();
        txnRequest.setTransactionType(TransactionTypeEnum.REFUND_TRANSACTION.value());
        txnRequest.setAmount(new BigDecimal(amount).setScale(2, RoundingMode.CEILING));
        txnRequest.setPayment(paymentType);
        txnRequest.setRefTransId(transId);

        //创建API请求并为此特定请求设置参数
        CreateTransactionRequest apiRequest = new CreateTransactionRequest();
        apiRequest.setMerchantAuthentication(merchantAuthenticationType);
        apiRequest.setTransactionRequest(txnRequest);

        // 呼叫控制器
        CreateTransactionController controller = new CreateTransactionController(apiRequest);
        controller.execute();

        // 得到回应
        CreateTransactionResponse response = controller.getApiResponse();

        log.info("authorize 退款操作返回结果: " + JSONObject.toJSONString(response));

        // 解析响应以确定结果
        if (response != null) {
            // 如果API响应正常，请继续检查事务响应
            if (response.getMessages().getResultCode() == MessageTypeEnum.OK) {
                TransactionResponse result = response.getTransactionResponse();
                if (result.getMessages() != null) {
                    return CommonResult.success("SUCCESS", result.getTransId());
                } else {
                    if (response.getTransactionResponse().getErrors() != null) {
                        return CommonResult.failMessage(500, "Authorize 申请退款失败", result.getErrors().getError().get(0).getErrorText());
                    }
                }
            } else {
                if (response.getTransactionResponse() != null && response.getTransactionResponse().getErrors() != null) {
                    return CommonResult.failMessage(500, "Authorize 申请退款异常", response.getTransactionResponse().getErrors().getError().get(0).getErrorText());
                } else {
                    return CommonResult.failMessage(500, "Authorize 申请退款异常", response.getMessages().getMessage().get(0).getText());
                }
            }
        } else {
            // 响应为空时显示错误代码和消息
            ANetApiResponse errorResponse = controller.getErrorResponse();
            if (!errorResponse.getMessages().getMessage().isEmpty()) {
                return CommonResult.failMessage(500, "Authorize 申请退款异常", errorResponse.getMessages().getMessage().get(0).getText());
            }
        }
        return CommonResult.fail(500, "NetworkTimeout");
    }

    @Override
    public CommonResult authorizeQuery(String transId) {
        // 设置环境沙盒或生产
        if (true) {
            ApiOperationBase.setEnvironment(Environment.SANDBOX);
        } else {
            ApiOperationBase.setEnvironment(Environment.PRODUCTION);
        }
        // 创建带有商家身份验证详细信息的对象
        MerchantAuthenticationType merchantAuthenticationType = new MerchantAuthenticationType();
        merchantAuthenticationType.setName(name);
        merchantAuthenticationType.setTransactionKey(transactionKey);

        GetTransactionDetailsRequest getRequest = new GetTransactionDetailsRequest();
        getRequest.setMerchantAuthentication(merchantAuthenticationType);
        getRequest.setTransId(transId);

        GetTransactionDetailsController controller = new GetTransactionDetailsController(getRequest);
        controller.execute();

        // 得到回应
        GetTransactionDetailsResponse response = controller.getApiResponse();

        log.info("authorize 查询操作返回结果: " + JSONObject.toJSONString(response));

        if (response != null) {
            if (response.getMessages().getResultCode() == MessageTypeEnum.OK) {
                return CommonResult.success("SUCCESS", response.getMessages().getMessage().get(0).getText());
            } else {
                log.error("authorize 查询订单未能获取信息:  {}", response.getMessages().getResultCode());
                return CommonResult.failMessage(500, "Authorize 支付查询失败", response.getMessages().getResultCode());
            }
        }
        return CommonResult.fail(500, "NetworkTimeout");
    }
}
